/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wiiscript;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 *
 * @author Evan
 */
public class AutoCompleteCombo extends JComboBox {
    private EditorPane pane;
    private String currentItem = null;
    private int clickCount = 0;
    public AutoCompleteCombo(EditorPane pane) {
        this.pane = pane;
        ItemListener itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED) {
                   currentItem = (String)e.getItem();
                   clickCount = -1;
                }
            }
        };
        addActionListener(new ComboListener());
        addItemListener(itemListener);
    }
    public void setData(String[] data) {
        removeAllItems();
        for(int i = 1; i < data.length; i++) {
            addItem(data[i]);
        }
    }

    private void append() {
        Document doc = pane.getDocument();
        try {
            int caretPosition = pane.getCaretPosition();
            doc.insertString(caretPosition, currentItem, null);
            pane.setCaretPosition(caretPosition + currentItem.length());
        } catch (BadLocationException ex) {
            Logger.getLogger(AutoCompleteCombo.class.getName()).log(Level.SEVERE, null, ex);
        }
        clickCount = 0;
        currentItem = "";
        pane.hideCodeComplete();
    }
    private class ComboListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("comboBoxChanged")) {
                if(clickCount > 0) {
                    append();
                } else {
                    clickCount++;
                }
            }
        }
    }
}
